package com.wd.tw.service;

import com.wd.tw.utils.TimeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import static com.wd.tw.constants.EleConstant.ELE_STATUS;
import static com.wd.tw.constants.EleConstant.ELE_TIME;

/**
 * @className: AsyncModBusService
 * @description: TODO 类描述
 * @author: liumingkun
 * @date: 2024/11/17
 **/
@Service
public class AsyncService {

    private final static Logger logger = LoggerFactory.getLogger(AsyncService.class);

    @Resource
    ModbusService modbusService;


    /**
     * 专用
     *
     * @param signal
     */
    @Async("taskExecutor")
    public void asyncSpecialSignal(int signal) {
        try {
            logger.info("异步专用发送(" + signal + ")，线程：" + Thread.currentThread().getName());
            modbusService.callEle(signal, true);
            ELE_STATUS.put(signal, true);
            Thread.sleep(1000 * 10 * 1);  // 模拟耗时任务
            logger.info("异步专用取消(" + signal + ")，线程：" + Thread.currentThread().getName());
            modbusService.callEle(signal, false);
            ELE_STATUS.put(signal, false);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }


    /**
     * 叫梯
     *
     * @param signal
     */
    @Async("taskExecutor")
    public void asyncCallSignal(Integer signal) {
        try {
            logger.info("异步叫梯发送(" + signal + ")，线程：" + Thread.currentThread().getName());
            modbusService.callEle(signal, true);
            Thread.sleep(1000 * 3 * 1);  // 模拟耗时任务
            logger.info("异步叫梯取消(" + signal + ")，线程：" + Thread.currentThread().getName());
            modbusService.callEle(signal, false);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }


    //15秒才能发送关闭信号
    public boolean needToSendSignal(Integer signal) {
        Long aLong = ELE_TIME.get(signal);
        Long curTime = TimeUtils.getCurrentTime();
        if (aLong == null) {
            ELE_TIME.put(signal, curTime);
            return true;
        }
        if (curTime - aLong >= 15) {
            ELE_TIME.put(signal, curTime);
            return true;
        } else {
            logger.info("Frequency too high:" + signal);
            return false;
        }
    }

}
